package lqb.manage;

import java.io.Reader;
import java.util.List;

import lqb.bean.User;
import lqb.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class UserService {
	private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static{
        try{
            reader    = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession(){
        return sqlSessionFactory;
    }
    
    
    public static void main(String[] args) {
    	
    	UserService userService=new UserService();
    	
    	System.out.println("--------------------------------------------------------");
    	User u=new User();
    	u.setPagebegin(0);
    	u.setPagesize(3);
    	System.out.println("-u.getCount()------"+u.getCount());
    	List<User> l=userService.selectPage(u);
    	System.out.println(l.size());
    	System.out.println("-u.getCount()------"+u.getCount());
    	System.out.println(l);
    	
    }
    
    
    public User selectById(int id){
    	SqlSession session = sqlSessionFactory.openSession();
    	UserMapper userMapper=session.getMapper(UserMapper.class);
        User user = userMapper.selectByID(id);
    	
    	session.close();
    	return user;
    }
    
    public List<User> selectPage(User u){
    	SqlSession session = sqlSessionFactory.openSession();
    	UserMapper userMapper=session.getMapper(UserMapper.class);
    	List<User> l = userMapper.selectPage(u);
    	return l;
    }
    
    
    public List<User> select(){
    	SqlSession session = sqlSessionFactory.openSession();
    	UserMapper userMapper=session.getMapper(UserMapper.class);
    	List<User> l = userMapper.select();
        
    	return l;
    }
    
    public int insert(User u){
    	SqlSession session = sqlSessionFactory.openSession();
    	UserMapper userMapper=session.getMapper(UserMapper.class);
    	int r = userMapper.insert(u);
    	
    	session.close();
    	return r;
    }
    
    public int update(User u){
    	SqlSession session = sqlSessionFactory.openSession();
    	UserMapper userMapper=session.getMapper(UserMapper.class);
    	int r = userMapper.update(u);
    	
    	session.close();
    	return r;
    }
    
    public int delete(User u){
    	SqlSession session = sqlSessionFactory.openSession();
    	//int r=  session.delete("lqb.mapper.UserMapper.delete",u);
    	
    	UserMapper userMapper=session.getMapper(UserMapper.class);
    	int r = userMapper.delete(u);
    	
    	session.close();
    	return r;
    }
    
}
